<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import stompService from '@/services/stompService';
import { ElScrollbar } from 'element-plus';

// bun add sockjs-client @stomp/stompjs
// bun add -d @types/sockjs-client
// 参考博客 https://blog.csdn.net/u013737132/article/details/135006370
// @stomp/stompjs 使用参考 https://www.npmjs.com/package/@stomp/stompjs

// 当发送消息后自动更新滚动条，参考 element-plus 官网 https://element-plus.org/zh-CN/component/scrollbar.html#%E6%89%8B%E5%8A%A8%E6%BB%9A%E5%8A%A8
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const innerRef = ref<HTMLDivElement>()

// 消息类型
export type Message = {
  // 消息ID
  messageId: string;
  // 发送者ID
  senderId: string;
  // 接收者ID 私聊时使用
  receiverId?: string;
  // 群组ID 群聊时使用
  groupId?: string;
  // 消息内容
  content: string;
  // 发送时间
  sendTime: string;
  // 消息类型
  type: 'private' | 'group';
};
// 当前用户输入的消息
const newMessage = ref("");
// 是一个响应式的数组，用来存储所有的聊天记录。
const messages = ref<Message[]>([]);
// 当前用户选择的群聊ID，应该从UI组件获取
const selectedGroupId = ref<string>('');
// 当前用户选择的私聊用户ID，应该从UI组件获取
const selectedReceiverId = ref<string>('');
// 群聊列表，假设这里是从API获取的数据
const groupChats = ref([
  { groupId: 'group-1', groupName: 'Group 1' },
  { groupId: 'group-2', groupName: 'Group 2' },
]);
// 私聊用户列表，假设这里是从API获取的数据
const users = ref([
  { userId: 'user-1', userName: 'User 1' },
  { userId: 'user-2', userName: 'User 2' },
  // ... 其他用户
]);

// 发送消息的方法
const sendMessage = (chatType: 'private' | 'group', destinationId?: string) => {
  if (newMessage.value.trim()) {
    // 创建消息对象
    const message: Message = {
      messageId: 'message-id', // 消息ID
      senderId: 'user-id', // 用户ID应该来自登录状态或其他方式获取
      receiverId: selectedReceiverId.value, // 私聊时使用
      groupId: selectedGroupId.value, // 群聊ID
      content: newMessage.value, // 消息内容
      type: chatType,
      ...(chatType === 'group' ? { groupId: destinationId } : {}),
      ...(chatType === 'private' ? { receiverId: destinationId } : {}),
      sendTime: new Date().toISOString(),
    };

    let destination = '/app/chat'; // 默认群聊目的地

    if (chatType === 'private') {
      destination = `/app/private/${message.receiverId}`; // 私聊目的地
    } else if (chatType === 'group') {
      destination = `/app/group/${message.groupId}`; // 群聊目的地
    }

    // 发送消息到服务器
    stompService.send(destination, {}, JSON.stringify(message));
    messages.value.push(message);
    // 发完消息后清空输入框
    newMessage.value = '';

    // 确保在消息列表更新后，DOM 已经反映了这些变更，然后将聊天窗口自动滚动到底部，让用户能够看到最新收到的消息。
    nextTick(() => {
      // scrollbarRef.value?.setScrollTop(scrollbarRef.value.wrap.offsetHeight);
      scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
    });
  }
};

// 发送群聊消息
const sendGroupMessage = () => {
  sendMessage('group', selectedGroupId.value);
};

// 发送私聊消息
const sendPrivateMessage = () => {
  sendMessage('private', selectedReceiverId.value);
};


// 处理接收到的消息
const handleMessage = (message: Message) => {
  console.log('Received message:', message)
  // const parsedMessage: Message = JSON.parse(message.body);

  messages.value.push(message);

  nextTick(() => {
    // scrollbarRef.value?.setScrollTop(scrollbarRef.value.wrap.offsetHeight);
    scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
  });
};


// 组件挂载时订阅消息
onMounted(() => {
  stompService.subscribe('/topic/messages', handleMessage);
});

// 组件卸载时断开连接
onUnmounted(() => {
  stompService.disconnect(() => console.log('Disconnected'));
});

</script>

<template>
  <div class="chat-container">
    <!-- 消息显示区 -->
    <el-scrollbar class="message-list" ref="scrollbarRef">
      <ul ref="innerRef">
        <li v-for="(message, index) in messages" :key="index" :class="['message', message.senderId === 'user' ? 'user-message' : '']">
          <span>{{ message.content }}</span>
        </li>
      </ul>
    </el-scrollbar>

    <!-- 输入框和发送按钮 -->
    <div class="input-area">
      <!-- 消息输入框 -->
      <el-input
          v-model="newMessage"
          style="width: 600px"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="请输入你的消息..."
          @keyup.enter="sendMessage"
          clearable
      />
      <el-button type="primary" @click="sendGroupMessage">发送到群聊</el-button>
      <el-button type="success" @click="sendPrivateMessage">发送到私聊</el-button>

      <!-- 群聊选择器示例 -->
      <el-select v-model="selectedGroupId" placeholder="请选择群聊">
        <el-option
            v-for="(group, index) in groupChats"
            :key="index"
            :label="group.groupName"
            :value="group.groupId"
        />
      </el-select>

      <!-- 私聊选择器示例 -->
      <el-select v-model="selectedReceiverId" placeholder="请选择用于私人聊天的用户">
        <el-option
            v-for="(user, index) in users"
            :key="index"
            :label="user.userName"
            :value="user.userId"
        />
      </el-select>
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.message-list {
  flex-grow: 1;
  padding: 10px;
  overflow-y: auto;
}

.message {
  padding: 5px 10px;
  margin-bottom: 5px;
  border-radius: 5px;
  background-color: #f0f0f0;
}

.user-message {
  background-color: #d1ecf9;
  text-align: right;
}

.input-area {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
}

.el-input {
  flex-grow: 1;
  margin-right: 10px;
}
</style>